/**
 * created by jsq on 2017/11/9
 * 2019/2/21优化代码 by zhouli
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import {Button, Table, Badge, Popconfirm, message} from 'antd';
import SearchArea from 'components/search-area';
import companyGroupService from 'containers/setting/company-group/company-group.service';
import config from 'config';
import menuRoute from 'routes/menuRoute';
import 'styles/setting/company-group/company-group.scss';
import ResizeTable from "components/resize-table";

class CompanyGroup extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: true,
      data: [],
      searchParams: {
        setOfBooksId: "",//this.props.company.setOfBooksId,
        companyGroupCode: "",
        companyGroupName: ""
      },
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchForm: [
        {
          type: 'select', id: 'setOfBooksId',
          label: messages('setting.key246'/*账套*/),
          options: [],
          renderOption: (option) => {
            return option.setOfBooksCode + "-" + option.setOfBooksName
          },
          //defaultValue: this.props.company.setOfBooksName,
          getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,
          method: 'get', labelKey: 'setOfBooksCode', valueKey: 'id',
          getParams: {roleType: 'TENANT'}
        },
        {
          type: 'input', id: 'companyGroupCode',
          label: messages('setting.key244'/*公司组代码*/)
        },
        {
          type: 'input', id: 'companyGroupName',
          label: messages('setting.key245'/*公司组名称*/)
        },
      ],
      columns: [
        {
          title: messages('setting.key244'/*公司组代码*/),
          key: "companyGroupCode", dataIndex: 'companyGroupCode'
        },
        {
          title: messages('setting.key245'/*公司组名称*/),
          key: "companyGroupName", dataIndex: 'companyGroupName'
        },
        {
          title: messages('setting.key246'/*账套*/),
          key: "setOfBooksName", dataIndex: 'setOfBooksName'
        },

        {
          title: messages('common.column.status'),
          key: 'status',
          width: '10%',
          dataIndex: 'enabled',
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages('common.status.enable') : messages('common.status.disable')}/>
          )
        },
        {
          title: messages('common.operation'), key: 'operation', width: '15%', render: (text, record) => (
          <span>
            <Popconfirm onConfirm={(e) => this.deleteItem(e, record)}
                        title={messages('setting.key1446', {controlRule: record.controlRuleName}/*你确认要删除？*/)}>
              <a href="#" onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
              }}>{messages('common.delete')}</a>
            </Popconfirm>
          </span>)
        },  //操作
      ],
    }
  }

  componentWillMount() {
    this.getList();
  }
  deleteItem = (e, record) => {
    this.setState({loading: true});
    companyGroupService.deleteCompanyGroupById(record.id).then(response => {
      message.success(messages('common.delete.success', {name: record.companyGroupName})); // name删除成功
      this.setState({
        loading: false
      }, this.getList);
    })
  };
  //获取公司组数据
  getList() {
    let params = this.state.searchParams;
    params.page = this.state.pagination.page;
    params.size = this.state.pagination.pageSize;
    companyGroupService.getCompanyGroupByOptions(params).then((response) => {
      response.data.map((item, index) => {
        item.key = item.id;
      });
      let pagination = this.state.pagination;
      pagination.total = Number(response.headers['x-total-count']);
      this.setState({
        data: response.data,
        pagination,
        loading: false
      })
    })
  };

  handleSearch = (values) => {
    let searchParams = {};
    let pagination = this.state.pagination;
    pagination.page = 0;
    pagination.pageSize = 10;
    pagination.current = 1;
    for (let key in values) {
      searchParams[key] = typeof values[key] !== 'undefined' ? values[key] : "";
    }
    this.setState({
      searchParams,
      pagination,
      loading: true,
    }, () => {
      this.getList();
    })
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        total: pagination.total
      }
    }, () => {
      this.getList();
    })
  };

  //新建公司组
  handleCreate = () => {
    this.context.router.push(menuRoute.getRouteItem('new-company-group').url.replace(':companyGroupId', 'NEW'));
  };

  //点击行，进入该行详情页面
  handleRowClick = (record, index, event) => {
    let url = menuRoute.getMenuItemByAttr('company-group', 'key').children.companyGroupDetail.url;
    url = url.replace(':id', record.id);
    this.context.router.push(url);
  };

  render() {
    const {searchForm, loading, data, columns, pagination} = this.state;
    return (
      <div className="budget-structure">
        <SearchArea searchForm={searchForm}
                    submitHandle={this.handleSearch}
                    clearHandle={() => {
                    }}/>
        <div className="table-header">
          <div className="table-header-title">
            {/*共搜索到*条数据*/}
            {messages('common.total', {total: `${pagination.total}`})}
          </div>
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleCreate}>
              {/*新 建*/}
              {messages('common.create')}
            </Button>
          </div>
        </div>
        <ResizeTable
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={pagination}
          onChange={this.onChangePager}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          size="middle"
          bordered
        />
      </div>
    )
  }
}

CompanyGroup.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(CompanyGroup);
